/*
* Copyright© 2018 Shanxi Lu'an Taihang Laihui Net Tech co.,LTD.
*/
package com.laihuichuxing.netty.server.server.module.login.handler;

import com.laihuichuxing.netty.common.core.exception.ErrorCodeException;
import com.laihuichuxing.netty.common.core.session.Session;
import com.laihuichuxing.netty.common.core.session.SessionManager;
import com.laihuichuxing.netty.server.server.module.Common;
import com.laihuichuxing.netty.server.server.module.login.entity.Login;
import com.laihuichuxing.netty.server.server.module.login.service.LoginService;
import com.laihuichuxing.protobuf.module.UserModule;
import com.laihuichuxing.socket.LoginCmd;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Description: 登录模块
 *
 * @author YangGuang
 * @since: 1.0
 * Create Date Time: 2018/7/16 16:13
 * Update Date Time:
 */
@Component
public class LoginHandlerImpl implements LoginHandler {

    private Logger logger = LoggerFactory.getLogger(LoginHandlerImpl.class);

    @Autowired
    private LoginService loginService;

    /**
     * 登录
     *
     * @param session session
     * @param data    data
     * @return
     */
    @Override
    public void login(Session session, byte[] data, Channel channel) {
        try {
            // 返序列化数据
            UserModule.User user = UserModule.User.parseFrom(data);
            int type = user.getType();
            String mobile = user.getMobile();
            String token = user.getToken();
            // 登录
            loginService.login(session, type, mobile, token, channel);
            // 通知客户端
            Common.LoginNotifyClient(session, LoginCmd.USER_LOGIN);
        } catch (ErrorCodeException e) {
            logger.error("登录异常:{}", e.toString(), e);
        } catch (Exception e) {
            logger.error("登录异常:{}", e.toString(), e);
        }
    }

    @Override
    public void testLogin(Session session, byte[] data) {
        try {
            // 返序列化数据
            UserModule.User user = UserModule.User.parseFrom(data);
            String mobile = user.getMobile();
            // 判断是否在其他地方登录过
            boolean isOnline = SessionManager.isOnline(mobile);
            if (isOnline) {
                // 移除会话,关闭连接
                SessionManager.removeSessionCloseSocket(mobile);
            }
            Login login = new Login();
            login.setMobile(mobile);
            // 加入会话
            if (SessionManager.putSession(mobile, session)) {
                session.setAttachment(login);
                logger.info("手机号为:{}的用户登录了", mobile);
            }
        } catch (Exception e) {
            logger.error("测试登录异常:" + e.toString(), e);
        }

    }
}
